<?php

namespace App\Http\Middleware;

use Closure,Config;
use Illuminate\Support\Facades\Auth;

class AdminAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {        
        if (Auth::guard($guard)->guest()) {
            if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest('login');
            }
        }
        $basepath = explode("/",$request->path());
        if (count($basepath) <= 2) {
            $route = [$request->path()];
        } else {
            $route = [$basepath[0]."/".$basepath[1].'/lists',$basepath[0]."/".$basepath[1].'/index'];
        }
        $menu = collect(Config::get("menu.menus"))->whereIn('route', $route)->first();
        if (!empty($menu)) {
            if (!in_array(Auth::user()->authority, $menu["auth"])) abort(404);
        }
        return $next($request);
    }
}
